package com.itheima.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.dto.PageComDto;
import com.itheima.commen.ReturnSuccess;
import com.itheima.pojo.SubjectsTags;
import com.itheima.service.SubjectsTagsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;


/**
 * 标签
 */

@RestController
@RequestMapping("/tags")
public class SubjectsTagsController {

    @Autowired
    private SubjectsTagsService subjectsTagsService;

    @Autowired
    private HttpServletRequest request;


    /**
     * 标签添加
     */
    @PostMapping
    public Integer add(@RequestBody SubjectsTags subjectsTags){
        //todo 待完善,从seeion中获取userId
        HttpSession session = request.getSession();
        Long userId = (Long) session.getAttribute("userId");
        String jsonString = JSON.toJSONString(userId);
        Integer uid = JSON.parseObject(jsonString, Integer.class);
        subjectsTags.setAddDate(new Date());
        subjectsTags.setState(1);
        subjectsTags.setCreatorId(uid);
        subjectsTags.setTotals(0);
        subjectsTagsService.save(subjectsTags);
        return subjectsTags.getId();
    }
    /**
     * 标签修改
     */
    @PutMapping("/{id}")
    public ReturnSuccess update(@RequestBody SubjectsTags subjectsTags,@PathVariable Integer id){
        if(subjectsTags==null){
            return ReturnSuccess.error();
        }
        subjectsTags.setId(id);
        subjectsTagsService.updateById(subjectsTags);
        return ReturnSuccess.success();
    }
    /**
     * 标签列表
     */
    @GetMapping
    public PageComDto findPage(Integer page,Integer pagesize,String tagName,Integer state){
        return subjectsTagsService.findPage(page,pagesize, tagName, state);
    }

    /**
     * 标签删除
     */
    @DeleteMapping("/{id}")
    public ReturnSuccess delete(@PathVariable Integer id){
        subjectsTagsService.removeById(id);
        return ReturnSuccess.success();
    }
    /**
     * 标签状态
     */
    @PostMapping("/{id}/{state}")
    public ReturnSuccess updateByState(@PathVariable Integer id,@PathVariable Integer state){
        LambdaUpdateWrapper<SubjectsTags> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(SubjectsTags::getId,id).set(SubjectsTags::getState,state);
        subjectsTagsService.update(wrapper);
        return ReturnSuccess.success();
    }
    /**
     * 标签详情
     */
    @GetMapping("/{id}")
    public SubjectsTags findById(@PathVariable Integer id){
        return subjectsTagsService.getById(id);
    }
}
